var express = require('express');
var router = express.Router();
var Department = require('../models/department')
var Util = require('../common/util');
/**
 * 创建部门
 */
router.post('/adddepartment',function (req,res,nex) {
    var params = req.body;
    if(!params){
        var dataError = {
            status: '0',
            msg: '参数不全'
        };
        res.end(JSON.stringify(dataError));
    }

    var depname = params.depname;
    var startusedstate = params.startusedstate;//启用状态

    if (!depname){
        var dataError = {
            status: '0',
            msg: '部门名称参数不全'
        };
        res.end(JSON.stringify(dataError));
    }

    else if(!Util(startusedstate)&&startusedstate!=0){
        var dataError = {
            status: '0',
            msg: '部门状态参数不全'
        };
        res.end(JSON.stringify(dataError));
    }


    Department.findOne({depname:depname,isdelete:"0"},function (err,dep) {
        if(err){
            var dataError = {
                status: '0',
                msg: err.message
            };
            res.end(JSON.stringify(dataError));
        }
        else if(dep){
            var dataError = {
                status: '0',
                msg: '部门名称已存在'
            };
            res.end(JSON.stringify(dataError));
        }
        else {
            var newDep = new Department({
                depname:depname,
                startusedstate: startusedstate
            });

            newDep.save(function (err) {
                if(err){
                    var dataError = {
                        status: '0',
                        msg: err.message
                    };
                    res.end(JSON.stringify(dataError));
                }
                else {
                    var dataSuccess = {
                        status: '1',
                        msg: '创建成功'
                    };
                    res.end(JSON.stringify(dataSuccess));
                }
            });
        }
    });
});

/**
 * 更新部门信息
 */
router.post('/updatedepartment',function (req,res,nex) {
    var params = req.body;
    if(!params){
        var dataError = {
            status: '0',
            msg: '参数不全'
        };
        res.end(JSON.stringify(dataError));
    }

    var id = params.id;
    var depname = params.depname;
    var startusedstate = params.startusedstate;//启用状态

    if (!depname){
        var dataError = {
            status: '0',
            msg: '部门名称参数不全'
        };
        res.end(JSON.stringify(dataError));
    }

    else if(!Util(startusedstate)&&startusedstate!=0){
        var dataError = {
            status: '0',
            msg: '部门状态参数不全'
        };
        res.end(JSON.stringify(dataError));
    }


    Department.findOne({depname:depname,isdelete:"0"},function (err,dep) {
        if(err){
            var dataError = {
                status: '0',
                msg: err.message
            };
            res.end(JSON.stringify(dataError));
        }
        else if(dep){
            if(dep._id != id){
                var dataError = {
                    status: '0',
                    msg: '部门名称已存在'
                };
                res.end(JSON.stringify(dataError));
            }
            else {
                var whereStr = {"_id":id};
                var updateStr = {$set: { "depname" : depname,"startusedstate" : startusedstate }};
                Department.update(whereStr,updateStr,function () {
                    if(err){
                        var dataError = {
                            status: '0',
                            msg: err.message
                        };
                        res.end(JSON.stringify(dataError));
                    }
                    else {
                        var dataSuccess = {
                            status: '1',
                            msg: '更新成功'
                        };
                        res.end(JSON.stringify(dataSuccess));
                    }

                });
            }
        }
        else {
            var whereStr = {"_id":id};
            var updateStr = {$set: { "depname" : depname,"startusedstate" : startusedstate }};
            Department.update(whereStr,updateStr,function () {
                if(err){
                    var dataError = {
                        status: '0',
                        msg: err.message
                    };
                    res.end(JSON.stringify(dataError));
                }
                else {
                    var dataSuccess = {
                        status: '1',
                        msg: '更新成功'
                    };
                    res.end(JSON.stringify(dataSuccess));
                }

            });
        }
    });
});

/**
 * 删除部门信息（更新字段，没有真正删除数据）
 */
router.post('/deletedepartment',function (req,res,nex) {
    var params = req.body;
    if(!params){
        var dataError = {
            status: '0',
            msg: '参数不全'
        };
        res.end(JSON.stringify(dataError));
    }

    var ids = params.ids;

    if (!ids){
        var dataError = {
            status: '0',
            msg: '没有选择删除部门'
        };
        res.end(JSON.stringify(dataError));
    }

    var array = ids.split(',');
    for(var i = 0 ;i <array.length ; i++ )
    {
        Department.update({"_id":array[i]},{"$set":{"isdelete":"1"}},function (err) {
            callMeBack(i);
        })
    }


    function callMeBack(index) {
        if(index == array.length){
            var dataSuccess = {
                status: '1',
                msg: '数据删除成功'
            };
            res.end(JSON.stringify(dataSuccess));
        }
    }

});

/**
 * 获取部门列表
 */
router.post('/departmentlist',function (req,res,nex) {
    var count = 0;
    var page = req.body.page;
    var rows = req.body.rows;
    var isdelete = req.body.isdelete;

    var depname = req.body.depname;
    var query = Department.find({});

    if(!page){
        page = 1;
    }

    if(!rows){
        rows = 10;
    }

    query.skip((page-1)*rows);


    query.limit(rows*1);


    if(depname){
        var qs=new RegExp(depname);
        query.where('depname',qs);
    }

    if(isdelete){
        query.where('isdelete',isdelete);
    }
    else {
        query.where('isdelete','0');
    }

    //计算分页数据
    query.exec(function(err,rs){
        if(err){
            var dataError = {
                status: '0',
                msg: err.message
            };
            res.end(JSON.stringify(dataError));


        }else{

            var qs=new RegExp(depname);
            Department.find({depname:qs,isdelete:'0'}).sort({'_id':-1}).exec(function (err,list) {


                if(err){
                    var dataError = {
                        status: '0',
                        msg: err.message
                    };
                    res.end(JSON.stringify(dataError));
                }
                else {
                    var dataSuccess = {
                        status: '1',
                        data:rs,
                        sumpage:list.length,
                        msg: '查询成功'
                    };
                    res.end(JSON.stringify(dataSuccess));
                }

            });

        }
    });
});


/**
 * 获取目前所有部门列表
 */
router.get('/getalldepartmentlist',function (req,res,nex) {
    var query = Department.find({});
    query.where('isdelete','0');
    query.where('startusedstate','0');

    //计算分页数据
    query.exec(function(err,rs){
        if(err){
            var dataError = {
                status: '0',
                msg: err.message
            };
            res.end(JSON.stringify(dataError));

        }else{
            var dataSuccess = {
                status: '1',
                data:rs,
                sumpage:rs.length,
                msg: '查询成功'
            };
            res.end(JSON.stringify(dataSuccess));
        }
    });
});


module.exports = router;
